#include <head.h>
typedef struct ct
{
    int size;
    int offset;
    char argv[20];
} ct;

void *get_size(void *arg) // 拷贝前半部分
{
    ct *s1 = (ct *)arg;
    printf("%s\n", s1->argv);
    int fd = open(s1->argv, O_RDONLY);
    if (fd == -1)
    {
        perror("open");
        return NULL;
    }
    struct stat st;
    if (-1 == fstat(fd, &st))
    {
        perror("fstat");
        return NULL;
    }
    sleep(3);
    int size = st.st_size; // 文件大小
    s1->size = size;
    pthread_exit((void *)&s1->size);
}

void *copy_1(void *arg) 
{
    ct *s2 = (ct *)arg;
    int src_fd = 0;

    int dest_fd = 0;

    // 打开源文件
    if (-1 == (src_fd = open(s2->argv, O_RDONLY)))
    {
        perror("open error");
        exit(-1);
    }
    // 打开目标文件
    if (-1 == (dest_fd = open(s2->argv, O_WRONLY)))
    {
        perror("open error");
        exit(-1);
    }

    // 定位光标
    lseek(src_fd, s2->offset, SEEK_SET);

    lseek(dest_fd, s2->offset, SEEK_SET);

    int ret = 0;
    int num = 0;
    char buf[64] = {0};

    while (true)
    {
        ret = read(src_fd, buf, sizeof(buf));

        if (0 == ret)
        {
            break;
        }

        num += ret;

        if (num > s2->size)
        {
            write(dest_fd, buf, s2->size - (num - ret));
            break;
        }

        write(dest_fd, buf, ret);
    }
    // 关闭文件
    close(src_fd);

    close(dest_fd);
}
int main(int argc, char const *argv[])
{
    // if (argc != 3)
    // {
    //     printf("./app <src> <dst>\n");
    //     return 0;
    // }
    ct s1[] = {{1, 20, "1.txt"},{2, 40, "2.txt"}};
    pthread_t tid1 = 0;
    pthread_t tid2 = 0;
    void *retval;
    pthread_create(&tid1, NULL, get_size, (void *)&s1[0]);
    pthread_create(&tid2, NULL, copy_1, (void *)&s1[1]);
    if (pthread_join(tid1, &retval) != 0)
    {
        fprintf(stderr, "Failed to join thread\n");
        return 1;
    }
    int *result = (int *)retval;
    printf("Main thread received value: %d\n", *result);

    return 0;
}
